package com.sunlee.admin.api.module.job.task;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sunlee.admin.api.module.job.dto.RandomUserActionTaskDTO;
import com.sunlee.common.service.entity.ProductEntity;
import com.sunlee.common.service.entity.UserActionEntity;
import com.sunlee.common.service.enums.StatusEnum;
import com.sunlee.common.service.service.ProductService;
import com.sunlee.common.service.service.UserActionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 随机生成用户行为数据
 *
 * @author sunlee
 * @date 2022/10/13
 */
@Component("randomUserActionTask")
public class RandomUserActionTask implements ITask {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserActionService userActionService;

    @Autowired
    private ProductService productService;

    @Override
    public void run(String params) {
        logger.info("randomUserActionTask定时任务正在执行，参数为：{}", params);
        RandomUserActionTaskDTO dto = JSON.parseObject(params, RandomUserActionTaskDTO.class);

        // 用户ID
        Long userId = Objects.nonNull(dto.getUserId()) ? dto.getUserId() : 0L;
        // 生成总数 5-10
        int total = Objects.nonNull(dto.getTotal()) ? dto.getTotal() : RandomUtil.randomInt(5, 11);
        // 商品范围
        Long productId = dto.getProductId();
        List<ProductEntity> randomProductList = null;
        if (Objects.isNull(productId)) {
            randomProductList = productService.selectList(
                    new LambdaQueryWrapper<ProductEntity>().last(" ORDER BY RAND() LIMIT " + total)
            );
        }

        // 当前时间
        Date date = new Date();
        List<UserActionEntity> userActionList = new ArrayList<>();
        for (int i = 0; i < total; i++) {
            userActionList.add(UserActionEntity.builder()
                    // 固定有效状态
                    .status(StatusEnum.VALID.getCode())
                    // 固定一个用户ID
                    .userId(userId)
                    // 固定一个更新时间
                    .updateDate(date)
                    // 固定一个创建时间
                    .createDate(date)
                    // 随机行为类型（1-3）
                    .actionType(Objects.nonNull(dto.getActionType()) ? dto.getActionType() : RandomUtil.randomInt(1, 4))
                    // 随机从范围取值(0-商品列表最大值)
                    .productId(Objects.nonNull(productId) ? productId :
                            randomProductList.get(RandomUtil.randomInt(0, randomProductList.size())).getId())
                    .build());
        }
        userActionService.saveBatch(userActionList);
    }
}